package com.cim.web;

import com.cim.config.GlobalConfig;
import com.cim.pojo.Account;
import com.cim.pojo.CourseAccount;
import com.cim.pojo.Video;
import com.cim.service.AccountService;
import com.cim.service.CourseAccountService;
import com.cim.service.CourseService;
import com.cim.service.VideoService;
import com.cim.utils.*;
import com.cim.pojo.Course;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

@Api(tags="课程相关")
@RestController
@RequestMapping("/api/course")
@Validated
public class CourseController {

    @Autowired
    private CourseService courseService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private CourseAccountService courseAccountService;

    //获取课程数据, 可传入条件进行筛选
    @ApiOperation(value="筛选课程",notes="可传入条件进行筛选,不传入条件则获取所有")
    @PostMapping("/getCourse")
    public Object getCourse(@RequestParam(defaultValue= "1") @ApiParam(value="页码") Integer index,
                            @RequestParam(defaultValue= "10") @ApiParam(value="页面大小") Integer pageSize,
                            @RequestParam(required = false) @ApiParam(value="课程标签") String courseClass,
                            @RequestParam(required = false) @ApiParam(value = "是否直播",defaultValue="false") String liveCourse,
                            @RequestParam(required = false) @ApiParam(value="课程来源") String courseSource){
        //课程标签列表
        List<Course> courses= new ArrayList<Course>();
        List<String> coursesId=new ArrayList<String>();
        if(courseClass!=null){
            String[] tags=courseClass.split(",");
            Course course=new Course();
            course.setLiveCourse(liveCourse);
            course.setCourseSource(courseSource);
            for(int i=0;i<tags.length;i++){
                course.setCourseClass(tags[i]);
                List<Course> temp= courseService.findCourses(course);
                for(Course c:temp){
                    boolean isin=false;
                    for(String id:coursesId){
                        if(id.equals(c.getCourseId())){
                            isin=true;
                            break;
                        }
                    }
                    if(isin==false){
                        coursesId.add(c.getCourseId());
                        courses.add(c);
                    }
                }
            }
        }else{
            Course course=new Course();
            course.setLiveCourse(liveCourse);
            course.setCourseSource(courseSource);
            List<Course> temp= courseService.findCourses(course);
            courses.addAll(temp);
        }

        PageUtil<Course> result=new PageUtil<>(new ArrayList<>(courses));
        result.setIndex(index);
        result.setPageSize(pageSize);
        return ResponseUtil.okList(result);
    }

    //查找课程数据 传入关键字进行搜索
    @ApiOperation(value="搜索课程",notes="使用传入的关键字在课程名、课程简介、教师名、教师简介中搜索")
    @PostMapping("/findCourse")
    public Object findCourse(@RequestParam(defaultValue= "1") @ApiParam(value="页码") Integer index,
                             @RequestParam(defaultValue= "10") @ApiParam(value="页面大小") Integer pageSize,
                             @RequestParam @ApiParam(value="搜索关键字") String keyWord){

        List<Course> list=courseService.findCourseByKeyWord(keyWord);
        PageUtil<Course> result=new PageUtil<>(list);
        result.setIndex(index);
        result.setPageSize(pageSize);
        return ResponseUtil.okList(result);
    }


    //搜索课程名
    @ApiOperation(value="课程名搜索",notes="使用课程名进行搜索,只返回关键信息,用于搜索框")
    @PostMapping("/searchByName")
    public Object searchByName(@RequestParam @ApiParam(value="关键字") String key,
                               @RequestParam(defaultValue= "1") @ApiParam(value="页码") Integer index,
                               @RequestParam(defaultValue= "10") @ApiParam(value="页面大小") Integer pageSize){
        List<Course> courseList=courseService.findCoursesByCourseName(key);
        List<String> courseNameList=new ArrayList<String>();
        for(Course course:courseList){
            courseNameList.add(course.getCourseName());
        }
        PageUtil<String> result=new PageUtil<>(courseNameList);
        result.setIndex(index);
        result.setPageSize(pageSize);
        return ResponseUtil.okList(result);
    }

    //通过ID获取课程详细信息(包括课程下的视频信息)
    @ApiOperation(value="获取课程+课程",notes="通过课程ID获取课程(包括课程下的视频)信息")
    @PostMapping("/getCourseById")
    public Object getCourseById(@RequestParam @ApiParam("课程ID") String courseId){
        Course course=courseService.getCourse(courseId);
        if(course==null){
            return ResponseUtil.ok();
        }
        Video video=new Video();
        video.setCourseId(course.getCourseId());
        List<Video> videos=videoService.findVideos(video);
        Map<Object,Object> result=new HashMap<Object,Object>();
        result.put("course",course);
        result.put("videos",videos);
        return ResponseUtil.ok(result);
    }

    //通过ID获取课程信息（不包括视频)
    @ApiOperation(value="获取课程",notes="通过ID获取课程信息")
    @PostMapping("/getCourseByIdLess")
    public Object getCourseByIdLess(@RequestParam @ApiParam("课程ID") String courseId){
        Course course=courseService.getCourse(courseId);
        if(course==null) {
            return ResponseUtil.ok();
        }
        return ResponseUtil.ok(course);
    }
    //创建课程
    @ApiOperation(value="创建课程",notes="教师创建课程")
    @PostMapping("/createCourse")
    public Object createCourse(@RequestParam @ApiParam("课程名") String courseName,
                               @RequestParam @ApiParam("课程标签") String courseClass,
                               @RequestParam @ApiParam("课程介绍") String courseIntroduce,
                               @RequestParam @ApiParam("课程教师") String courseTeacher,
                               @RequestParam @ApiParam("教师介绍") String teacherIntroduce,
                               @RequestParam @ApiParam("课程来源") String courseSource,
                               @RequestParam @ApiParam("课程封面") String courseImg,
                               @RequestParam @ApiParam("直播课程") String liveCourse,
                               HttpServletRequest request){
        String role=(String)request.getAttribute(GlobalConfig.TOKEN_ROLE);
        String user=(String)request.getAttribute(GlobalConfig.TOKEN_USER);
        Account account=accountService.getAccountByUserName(user);
        if(role!=null&&role.equals("true")&&account!=null){
            String currentTime=String.valueOf(System.currentTimeMillis()/1000);
            Course req=new Course(courseName,null,courseClass,courseIntroduce,courseTeacher,teacherIntroduce,courseSource,courseImg,liveCourse,currentTime,currentTime);
            req.setCreateTime(String.valueOf(((System.currentTimeMillis()/1000))));
            Course res=courseService.addCourse(req);
            CourseAccount courseAccount=new CourseAccount();
            courseAccount.setCourseId(res.getCourseId());
            courseAccount.setUserId(account.getUserId());
            courseAccountService.addCourseAccount(courseAccount);
            return ResponseUtil.ok(res);
        }else{
            return ResponseUtil.unauthz();
        }
    }

    //删除课程
    @ApiOperation(value="删除课程",notes="通过课程Id删除课程")
    @PostMapping("/deleteCourse")
    public Object deleteCourse(@RequestParam @ApiParam("课程Id") String courseId,HttpServletRequest request){
        String userName= (String) request.getAttribute(GlobalConfig.TOKEN_USER);
        String role= (String) request.getAttribute(GlobalConfig.TOKEN_ROLE);
        Account ac=accountService.getAccountByUserName(userName);
        if(role==null||!role.equals("true")){       //判断角色是否是教师
            return ResponseUtil.unauthz();
        }
        //判断课程是否存在
        Course course=courseService.getCourse(courseId);
        if(course==null){       //不存在，直接返回OK
            return ResponseUtil.ok();
        }
        //判断用户与课程关系
        CourseAccount courseAccount=courseAccountService.findByCA(ac.getUserId(),courseId);
        if(courseAccount==null){    //如果该教师与课程无关
            return ResponseUtil.unauthz();  //提示没有权限
        }
        //课程存在 且 与该教师有关 则 删除课程 并删除关系
        courseAccountService.deleteCourseAccountByCourseId(courseAccount.getCourseId());
        //删除课程之前先删除依赖课程的视频
        videoService.deleteByCourseId(courseId);
        courseService.deleteCourse(courseId);
        return ResponseUtil.ok();
    }

    @ApiOperation(value="修改课程",notes="修改课程信息")
    @PostMapping("/modifiCourse")
    public Object modifiCourse(
                        @RequestParam @ApiParam("课程ID") String courseId,
                        @RequestParam @ApiParam("课程名") String courseName,
                        @RequestParam @ApiParam("课程标签") String courseClass,
                        @RequestParam @ApiParam("课程介绍") String courseIntroduce,
                        @RequestParam @ApiParam("课程教师") String courseTeacher,
                        @RequestParam @ApiParam("教师介绍") String teacherIntroduce,
                        @RequestParam @ApiParam("课程来源") String courseSource,
                        @RequestParam @ApiParam("课程封面") String courseImg,
                        HttpServletRequest request){
        String role=(String)request.getAttribute(GlobalConfig.TOKEN_ROLE);
        String userName=(String)request.getAttribute(GlobalConfig.TOKEN_USER);
        Account account=accountService.getAccountByUserName(userName);
        Course course=courseService.getCourse(courseId);
        if(course==null){
            return ResponseUtil.fail(404,"找不到课程");
        }
        if(role!=null&&role.equals("true")){
            CourseAccount courseAccount=courseAccountService.findByCA(account.getUserId(),courseId);
            if(userName!=null&&courseAccount!=null){
                //开始修改
                course.setCourseName(courseName);
                course.setCourseClass(courseClass);
                course.setCourseIntroduce(courseIntroduce);
                course.setCourseTeacher(courseTeacher);
                course.setTeacherIntroduce(teacherIntroduce);
                course.setCourseSource(courseSource);
                course.setCourseImg(courseImg);
                courseService.updateCourse(course);
                return ResponseUtil.ok(course);
            }else{
                return ResponseUtil.unauthz();
            }
        }else{
            return ResponseUtil.unauthz();
        }
    }
}
